package com.aimuceliang.aimuceliang.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.aimuceliang.aimuceliang.AppManager;
import com.aimuceliang.aimuceliang.dev.R;
import com.aimuceliang.aimuceliang.ui.BaseActivity;
import com.aimuceliang.aimuceliang.utils.BluetoothManager;
import com.aimuceliang.aimuceliang.utils.T;
import com.aimuceliang.aimuceliang.utils.XLog;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by 80470 on 2017/7/23.
 * 首页
 */

public class MainActivity extends BaseActivity {
    public static final int MY_PERMISSION_REQUEST_CONSTANT = 1;
    @BindView(R.id.tv_status_bluetooth)
    TextView vTvStatusBluetooth;
    @BindView(R.id.tv_bluetooth_name)
    TextView vTvBluetoothName;
    @BindView(R.id.iv_status_bluetooth)
    ImageView vIvStatusBluetooth;
//    @BindView(R.id.iv_tips_longcheng)
//    ImageView vIvTipsLongcheng;
    @BindView(R.id.iv_tips_wocheng)
    ImageView vIvTipsWocheng;
    @BindView(R.id.iv_tips_celiang)
    ImageView vIvTipsCeliang;

    private long backPressTime;
    private AlertDialog dialog;

    @Override
    protected int initContentView() {
        return R.layout.activity_main;
    }

    @Override
    protected void initUIAndListener() {
        if (BluetoothManager.isBluetoothSupported()) {
            if (!BluetoothManager.isBluetoothEnabled()) {
                setStatus(false, "蓝牙未开启", "");
                initDialog();
            } else {
                setStatus(true, "蓝牙已开启", "");
            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (BluetoothManager.isBluetoothSupported()) {
            if (!BluetoothManager.isBluetoothEnabled()) {
                setStatus(false, "蓝牙未开启", "");
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
            } else {
                setStatus(true, "蓝牙已开启", "");
            }
        }
    }

    private void initDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.layout_yesorno_dialog, null);
        ViewHolder holder = new ViewHolder(view);
        holder.tvCancel.setOnClickListener(v -> dialog.dismiss());
        holder.tvEnsure.setOnClickListener(v -> {
            boolean turnOnBluetooth = BluetoothManager.turnOnBluetooth();
            if (!turnOnBluetooth) {
                T.showShort("自动打开蓝牙失败,请手动打开蓝牙!");
            } else {
                setStatus(true, "蓝牙已开启", "");
                dialog.dismiss();
            }
        });
        builder.setView(view);
        builder.setCancelable(false);
        dialog = builder.create();
        dialog.show();
    }

    @Override
    protected void initData() {
        if (Build.VERSION.SDK_INT >= 6.0) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSION_REQUEST_CONSTANT);
            } else {

            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {

        switch (requestCode) {
            case MY_PERMISSION_REQUEST_CONSTANT: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
                    Toast.makeText(this, "无法查找蓝牙设备", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }

    /**
     * 设置首页上面三个控件的状态,由于要多次使用,故而封装
     **/
    private void setStatus(boolean status, String bName, String bStatus) {
        if (status) {
            vIvStatusBluetooth.setImageResource(R.mipmap.blue_open);
        } else {
            vIvStatusBluetooth.setImageResource(R.mipmap.blue_off);
        }
        vTvStatusBluetooth.setText(bStatus);
        vTvBluetoothName.setText(bName);
    }

    @OnClick({/*R.id.layout_longcheng, */R.id.layout_wocheng, R.id.layout_celiang, R.id.layout_Settings})
    public void onClick(View view) {
        Intent intent = new Intent(this, ChooseBluetoothActivity.class);
        switch (view.getId()) {
            /*
            case R.id.layout_longcheng://笼秤
                intent.putExtra("title", "笼秤");
                intent.putExtra("DeviceType", "1");
                startActivity(intent);
                break;
            */
            case R.id.layout_wocheng://窝秤
                intent.putExtra("title", "窝秤");
                intent.putExtra("DeviceType", "2");
                startActivity(intent);
                break;
            case R.id.layout_celiang://测量
                intent.putExtra("title", "体尺测量");
                intent.putExtra("DeviceType", "3");
                startActivity(intent);
                break;
            case R.id.layout_Settings://设置
                startActivity(SettingsActivity.class);
                break;
        }
    }

    // 再按一次退出程序
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN
                && event.getRepeatCount() == 0) {
            long current = System.currentTimeMillis();
            if (current - backPressTime > 2000) {
                backPressTime = current;
                T.showShort("再次按返回键退出程序");
            } else {
                XLog.i("MainActivity", "Exiting...");
                AppManager.getAppManager().AppExit(MainActivity.this);
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    static class ViewHolder {
        @BindView(R.id.tv_info)
        TextView tvInfo;
        @BindView(R.id.tv_cancel)
        TextView tvCancel;
        @BindView(R.id.tv_ensure)
        TextView tvEnsure;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
